$(function(){
	/**
	 * 初始化html，引入JS即创建该div
	 */
	$('body').append($('<div class="pushDown"></div>'))
	$('.pushDown').append($('<div class="pushDownOn"></div>'))
	$('.pushDownOn').append($('<p>松开加载</p>'))
	$('.pushDown').append($('<div class="pushDownOut"></div>'))
	$('.pushDownOut').append($('<p>正在加载 ...</p>'))
});

var bind = (function(){
	/**
	 * 上滑刷新
	 * @type {Object}
	 */
	var pull = {
		/**
		 * 第一步：上滑
		 * @param {Number} dist 上滑高度
		 */
		pullUp:function(dist){
			$('.pushDownOn').css('display','block');
			$('.pushDownOut').css('display','none');
			$('.pushDownOn').css('height',(dist-20) + "px");
		},
		/**
		 * 第二步：上滑结束
		 * @return {[type]} [description]
		 */
		pullDown:function(){
			$('.pushDownOn').css('display','none');
			$('.pushDownOut').css('display','block');
			$('.pushDownOn').css('height','20px');
		},
		/**
		 * 加载过程结束
		 * @return {[type]} [description]
		 */
		pullEnd:function(){
			$('.pushDownOn').css('display','none');
			$('.pushDownOut').css('display','none');
		}
	}
	
	var options;
	var callback;
	pullAndLoad();
	/**
	 * 外界调用刷新接口
	 * @param {JSON} options 接口调用参数
	 * @example
	 * options:{url:'www.hanfang360.com',params:{'id':'123','name':'test',isEnd:false},method:'get'}
	 * @param  {Function} callback 获取数据后调用函数
	 */
	function pullAndLoad(){
		var start = 0,end = 0;
		document.addEventListener("touchstart",touchStart,false);
		document.addEventListener("touchmove",touchMove,false);
		document.addEventListener("touchend",touchEnd,false);
		function touchStart(event){
			if($('.pushDownOut').css('display')=='block' || options.isEnd){
				return;
			}
			var touch = event.targetTouches[0];
			start = touch.pageY;
		}
		function touchMove(event){
			if($('.pushDownOut').css('display')=='block' || options.isEnd){
				return;
			}
			var touch = event.targetTouches[0];
			end = (start - touch.pageY);
			//在有移动距离的时候调用上拉接口，最高为50
			if(end > 0 && end < 50){
				pull.pullUp(end);
			}
		}
		function touchEnd(event){
			if($('.pushDownOut').css('display')=='block' || options.isEnd){
				return;
			}
			if(end > 0){
				//console.log("上滑  "+end);
				pull.pullDown();
				//刷新成功复原状态
				setTimeout(function(){
					options.isEnd = true;
					var data = {id:'1',item:'end'};
					for(var p in $($('#tempId')[0])){
						//console.log($('#tempId')[0][p]+'--');
					}
					
					callback(data);
					pull.pullEnd();
				},1500);
				/*$.post(options.url,options.params,function(data){
					pull.pullEnd();
				});*/
			}
		}
	}
	return {
		setOptions:function(newOptions,newCallback){
			options = newOptions;
			callback = newCallback;
		}
	}
})();